package com.ithui.tidal.common.config;

import com.ithui.tidal.common.thread.MyThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {
    /**
     * 项目共用线程池
     */
    public static final String TIDAL_EXECUTOR = "tidalExecutor";
    /**
     * websocket通信线程池
     */
    public static final String WS_EXECUTOR = "websocketExecutor";

    @Override
    public Executor getAsyncExecutor() {
        return tidalExecutor();
    }

    @Bean(TIDAL_EXECUTOR)
    @Primary // 优先使用该线程池
    public ThreadPoolTaskExecutor tidalExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setWaitForTasksToCompleteOnShutdown(true); // 等待任务完成后关闭线程池 线程池优雅停机的关键
        executor.setCorePoolSize(10); // 核心线程数
        executor.setMaxPoolSize(10); // 最大线程数
        executor.setQueueCapacity(200); // 队列容量
        executor.setThreadNamePrefix("tidal-executor-"); // 线程名前缀
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//满了调用线程执行，认为重要任务
        executor.setThreadFactory(new MyThreadFactory(executor)); // 自定义线程工厂，处理线程的异常
        executor.initialize(); // 初始化线程池
        return executor;
    }

    /**
     * 其他地方使用该线程池
     */
   /* @Autowired
    @Qualifier(ThreadPoolConfig.TIDAL_EXECUTOR) // 优先使用该线程池
    private ThreadPoolExecutor threadPoolExecutor;*/

}